#!/bin/bash
# 服务状态检查脚本

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

echo "========================================="
echo "  微服务状态检查"
echo "========================================="
echo ""

# 检查Redis
echo "【Redis状态】"
if redis-cli ping > /dev/null 2>&1; then
    echo -e "${GREEN}✓ Redis运行中${NC}"
else
    echo -e "${RED}✗ Redis未运行${NC}"
fi
echo ""

# 检查注册的服务
echo "【服务注册信息】"
SERVICES=("PingService" "UserService" "FileService")

for service in "${SERVICES[@]}"; do
    INSTANCE_COUNT=$(redis-cli HLEN service:$service:instances 2>/dev/null || echo 0)
    
    if [ "$INSTANCE_COUNT" -gt 0 ]; then
        echo -e "${GREEN}✓ $service: $INSTANCE_COUNT 个实例${NC}"
        
        # 显示实例详情
        redis-cli HGETALL service:$service:instances 2>/dev/null | while read -r key; do
            read -r value
            if [ ! -z "$key" ]; then
                PORT=$(echo "$value" | grep -o '"port":[0-9]*' | cut -d: -f2)
                HEARTBEAT_KEY="service:heartbeat:$key"
                
                if redis-cli EXISTS "$HEARTBEAT_KEY" > /dev/null 2>&1; then
                    TTL=$(redis-cli TTL "$HEARTBEAT_KEY")
                    echo -e "  - $key @ :$PORT ${GREEN}(心跳: ${TTL}s)${NC}"
                else
                    echo -e "  - $key @ :$PORT ${RED}(无心跳)${NC}"
                fi
            fi
        done
    else
        echo -e "${YELLOW}⚠ $service: 无实例${NC}"
    fi
done
echo ""

# 检查进程
echo "【进程状态】"
for pid_file in /tmp/ping_service_*.pid; do
    if [ -f "$pid_file" ]; then
        PID=$(cat "$pid_file")
        PORT=$(basename "$pid_file" .pid | sed 's/ping_service_//')
        
        if kill -0 $PID 2>/dev/null; then
            echo -e "${GREEN}✓ PingService:$PORT (PID=$PID) 运行中${NC}"
        else
            echo -e "${RED}✗ PingService:$PORT (PID=$PID) 已停止${NC}"
        fi
    fi
done

if [ ! -f /tmp/ping_service_*.pid ]; then
    echo -e "${YELLOW}⚠ 无运行的服务进程${NC}"
fi

echo ""
echo "========================================="
